import axios, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { message } from 'antd'
import sgs_util from '@/src/util/index'
import $ajax from '@/types/sgs/lib.request'
import systemConfig from '@/config/system.config'


class request implements $ajax {
    /** 请求默认参数 */
    protected requestParam: AxiosRequestConfig = {
        baseURL: systemConfig.baseUrl + 'api/v1/',
        auth: {
            username: 'sanmu',
            password: 'sa123'
        },
    }

    /** axios 实例 */
    protected axios: AxiosInstance

    /* */
    protected get source() {
        return axios.CancelToken.source()
    }

    constructor() {
        this.axios = axios.create({ ...this.requestParam })
        // 拦截请求
        this.axios.interceptors.request.use(
            config => {
                if (config.method == 'post') {

                } else {
                    const _token = sgs_util.getStorage('token')
                    if (_token) config.headers['token'] = _token
                    else {
                        message.error({
                            content: '请登录后操作'
                        })
                    }
                }
                return config
            },
            error => {
                message.error({
                    content: error.message
                })
                return Promise.reject(error)
            }
        )

        // 拦截响应
        this.axios.interceptors.response.use(
            response => {
                return response
            },
            error => {
                message.error({
                    content: error.message
                })
                return Promise.reject(error)
            }

        )
    }


    public get: $ajax['get'] = async (option) => {
        const res = await this.axios.get(option.url, { cancelToken: this.source.token })
        return res.data
    }
}

export default <$ajax>(new request())